<template>
  <section>
    <div>
       <el-button type="primary" size="mini" @click="handleClick0" v-if="getOperation('insert')">{{$t('area.sameLevel')}}</el-button>
       <el-button type="primary" size="mini" @click="handleClick1" v-if="getOperation('insert')">{{$t('area.nextLevel')}}</el-button>
       <el-button type="warning" size="mini" @click="handleClick2" v-if="getOperation('update')">{{$t('modify')}}</el-button>
       <el-button type="danger" size="mini" @click="handleClick3" v-if="getOperation('delete')">{{$t('delete')}}</el-button>

      <!--<el-button type="primary" size="mini" @click="handleClick0">添加同级</el-button>
      <el-button type="primary" size="mini" @click="handleClick1">添加下级</el-button>
      <el-button type="warning" size="mini" @click="handleClick2">修改</el-button>
      <el-button type="danger" size="mini" @click="handleClick3">删除</el-button>-->

      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        node-key="id"
        lazy
        :load="loadMethod"/>

      <el-dialog width="90%" top="20px" :title="dialogForm.form.id==0?$t('add'):$t('modify')" :visible.sync="dialogForm.visible"
                 :close-on-click-modal="false" :modal-append-to-body="false">
        <el-form :model="dialogForm.form" label-width="80px" :rules="dialogForm.rules" ref="formData">
          <el-form-item prop="parentId" label="" v-show="false">
            <el-input v-model="dialogForm.form['parentId']"></el-input>
          </el-form-item>
          <el-form-item prop="name" :label="$t('area.name')">
            <el-input v-model="dialogForm.form['name']" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="level" :label="$t('area.level')" v-show="false">
            <el-input-number v-model.number="dialogForm.form['level']"></el-input-number>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button @click="dialogForm.cancelHandler">{{$t('cancel')}}</el-button>
          <el-button @click="dialogForm.submitHandler" type="primary">{{$t('submit')}}</el-button>
        </div>
      </el-dialog>
    </div>

  </section>
</template>

<script>

  /*#region 导入函数*/

  import {AreaAPI} from "../../../modules";

  /*#endregion*/

  export default {
    methods: {

      /*#region 数据提交事件*/
      updateParentNodeLeafFlag(parentId, action, onSuccess) {
        const tree = this.$refs.tree;
        //console.log('updateParentNodeLeafFlag=='+parentId+',action'+action)
        if (action === "remove") {
          if (parentId) {
            const parentNode = tree.getNode(parentId);
            if (parentNode.childNodes.length < 2) {
              const data = parentNode.data;
              AreaAPI.updateArea({
                ...data,
                leafFlag: true
              });
            }
          }
        } else {
          // append
          if (parentId) {
            const parentNode = tree.getNode(parentId);
            if (parentNode.isLeaf) {
              const data = parentNode.data;
              // 是叶子节点
              AreaAPI.updateArea({
                ...data,
                leafFlag: false
              }).then(() => typeof onSuccess === "function" && onSuccess());
            }
          }
        }
      },

      /*#endregion*/

      /*#region 操作函数(handle)*/
      handleClick0() {
        // 同级
        const tree = this.$refs.tree;
        const data = tree.getCurrentNode();
        if (data) {
          const level = tree.getNode(data.id).level;
          // prepare form and dialog status.
          this.dialogForm.form = {
            id: 0,
            parentId: data.parentId || 0,
            name: null,
            level,
            leafFlag: true
          };

          this.dialogForm.status = 0; // stand for create
          this.dialogForm.visible = true;
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate();
          });

        } else {
          this.$message.error(this.$t('area.selectNode'));
        }
      },

      handleClick1() {
        // 下级
        const tree = this.$refs.tree;
        const data = tree.getCurrentNode();
        if (data) {
          const level = tree.getNode(data.id).level + 1;
          // prepare form and dialog status.
          this.dialogForm.form = {
            id: 0,
            parentId: data.id,
            name: null,
            level,
            leafFlag: true
          };

          this.dialogForm.status = 1; // stand for create
          this.dialogForm.visible = true;
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate();
          });

        } else {
          this.$message.error(this.$t('area.selectNode'));
        }
      },

      handleClick2() {
        // modify
        const tree = this.$refs.tree;
        const data = tree.getCurrentNode();
        if (data) {
          // prepare form and dialog status.
          for (const k in this.dialogForm.form) {
            if (k !== null) {
              this.dialogForm.form[k] = data[k];
            }
          }

          this.dialogForm.status = 2;
          this.dialogForm.visible = true;
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate();
          });

        } else {
          this.$message.error(this.$t('area.selectNode'));
        }
      },
      handleClick3() {
        // delete
        const tree = this.$refs.tree;
        const data = tree.getCurrentNode(); // element bug, node is actually data.
        //console.log(data);
        if (data) {
          const id = data.id;
          const parentId = data.parentId;

          this.$confirm(this.$t('area.deleteConfirm'), this.$t('confirm'), {
            confirmButtonText: this.$t('confirm'),
            cancelButtonText: this.$t('cancel'),
            type: "warning"
          }).then(() => {
            AreaAPI.deleteArea({id: id}).then((res) => {
              this.$report(res.data, "destroy", () => {

                this.loadMethod(this.root, Promise.resolve);
              });
            });
          });
        } else {
          this.$message.error(this.$t('area.selectNode'));
        }
      },

      /*#endregion*/

      /*#region 获取数据*/
      fetchAreaByParentId(parentId) {
        return new Promise((resolve) => {
          AreaAPI.listArea({parentId: parentId, orderBy: "Id desc"})
          .then((res) => {
            resolve(
              res.data.data.data.map((it) => (
                {...it, label: it.name}
              ))
            );
          });
        });
      },

      loadMethod(node, resolve) {
        if (node.level === 0) {
          this.root = node;
          // load root
          this.fetchAreaByParentId(0).then((data) => this.data = data);
        } else {
          if (node.childNodes.length === 0 && !node.isLeaf) {
            const parentId = node.data.id;
            this.fetchAreaByParentId(parentId)
            .then((data) => resolve(data));
          }
        }
      }

      /*#endregion*/

    },

    /*#region 生命周期函数(created、mount、等)*/
    created() {
      this.dialogForm.cancelHandler = this.dialogForm.cancelHandler.bind(this);
      this.dialogForm.submitHandler = this.dialogForm.submitHandler.bind(this);
    },

    /*#endregion*/
    /*#region 注册绑定数据*/
    data() {
      return {
        defaultProps: {
          label: "label",
          isLeaf: "leafFlag"
        },
        data: [],
        root: {},
        dialogForm: {
          visible: false,
          status: 0,
          form: {
            id: 0,
            parentId: null,
            name: null,
            level: null
            // leafFlag: null,
          },

          rules: {
            name: [{required: true, message: this.$t('area.validateName')}]
          },

          cancelHandler: function () {
            this.dialogForm.visible = false;
          },

          /*#region 数据提交事件*/
          submitHandler: function () {
            if (this.dialogForm.status === 0) {
              // create click0
              this.$refs.formData.validate((valid) => {
                if (valid) {
                  const form = this.dialogForm.form;

                  AreaAPI.insertArea(form).then((res) => {
                    this.$report(res.data, "create", () => {
                      this.dialogForm.cancelHandler();
                    });
                    this.loadMethod(this.root, Promise.resolve);
                  });
                }
              });
            } else if (this.dialogForm.status === 1) {
              // create click1
              this.$refs.formData.validate((valid) => {
                if (valid) {
                  const form = this.dialogForm.form;
                  AreaAPI.insertArea(form).then((res) => {
                    this.$report(res.data, "create", () => {
                      this.dialogForm.cancelHandler();
                      const tree = this.$refs.tree;
                      const data = tree.getCurrentNode();
                      // 更新节点的leafFlag
                      this.updateParentNodeLeafFlag(data.id, "append", () => {
                        //
                      });
                      this.loadMethod(this.root, Promise.resolve);
                    });
                  });
                }
              });
            } else {
              // update click2
              this.$refs.formData.validate((valid) => {
                if (valid) {
                  const form = this.dialogForm.form;
                  AreaAPI.updateArea(form).then((res) => {
                    this.$report(res.data, "update", () => {
                      this.dialogForm.cancelHandler();
                      // update locally.
                      /*const tree = this.$refs.tree
                      let node = tree.getNode(form.id)*/

                      this.loadMethod(this.root, Promise.resolve);

                      /*  tree.insertBefore({
                          form, label: form.name
                        }, node)
                        tree.remove(node)*/
                    });
                  });
                }
              });
            }
          }

    /*#endregion*/
        }
      };
    }

    /*#endregion*/
  };

</script>

<style scoped>

</style>
